package LinkedList;

public class LinkedList {

    private Node head;

    public LinkedList() {
        head = null;
    }

    public LinkedList(Node head) {
        this.head = head;
    }

    public LinkedList(int value) {
        head = new Node(value);
    }

    @Override
    public String toString() {
        if (head == null) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        Node current = head;
        while (current != null) {
            sb.append(current.value);
            current = current.next;
            if (current != null) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    /**
     * 尾插法
     *
     * @param value
     */
    public LinkedList append(int value) {
        if (head == null) {
            head = new Node(value);
            return this;
        }

        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = new Node(value);
        return this;
    }

    /**
     * 首插法
     *
     * @param value
     * @return
     */
    public LinkedList prepend(int value) {
        var newHead = new Node(value);
        newHead.next = head;
        head = newHead;
        return this;
    }

    /**
     * 插入
     * 
     * @param pos   位置
     * @param value 值
     * @return
     */
    public LinkedList insert(int pos, int value) {
        // 位置异常
        if (pos < 0) {
            throw new IllegalArgumentException("pos is less than 0");
        }
        // 首位置插入，直接调用
        if (pos == 0) {
            prepend(value);
        }
        // 已经在尾部了
        if (head == null) {
            throw new ArrayIndexOutOfBoundsException("head is null");
        }

        var previous = head;
        var current = head.next;
        var i = 1;
        while (i < pos) {
            // 总共5个元素，但是你要插入第十个，所有需要判断当前
            if (current == null) {
                throw new ArrayIndexOutOfBoundsException("current is null");
            }
            previous = current;
            current = current.next;
            i++;
        }
        var newHead = new Node(value);
        newHead.next = current;
        previous.next = newHead;

        return this;
    }

}
